package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IMenuService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("menu")
public class MenuController {

    @Autowired
    IMenuService menuService;

    @RequestMapping("view")
    @RequiresPermissions(value = {"menu:view","菜单页面"},logical = Logical.OR)
    public String view() {
        return "menu";
    }

    @RequestMapping("query")
    @ResponseBody
    @RequiresPermissions(value = {"menu:query","菜单列表"},logical = Logical.OR)
    public PageResult query(QueryObject qo) {
        return menuService.query(qo);
    }

    @RequestMapping("selectRootMenu")
    @ResponseBody
    public List<Menu> selectRootMenu() {
        return menuService.selectRootMenu();
    }
    @RequestMapping("selectEmployeeMenu")
    @ResponseBody
    public List<Menu> selectEmployeeMenu() {
        return menuService.selectEmployeeMenu();
    }

    @RequestMapping("delete")
    @ResponseBody
    @RequiresPermissions(value = {"menu:delete","菜单删除"},logical = Logical.OR)
    public JsonResult delete(Long id) {
        try {
            menuService.deleteById(id);
            return JsonResult.success("");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.mark("操作失败");
        }
    }

    @RequestMapping("validateMenuText")
    @ResponseBody
    public boolean validateMenuText(String menuText, Long id) {
        Menu menu = menuService.validateMenuText(menuText);
        return menu == null || menu.getId() == id;
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    @RequiresPermissions(value = {"menu:saveOrUpdate","菜单新增/更改"},logical = Logical.OR)
    public JsonResult saveOrUpdate(Menu dept) {
        try {
            if (dept.getId() != null) {
                menuService.updateByPrimaryKey(dept);
            } else {
                //保存新的员工要设置默认的状态为在职
                menuService.insert(dept);
            }
            return JsonResult.success("");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.mark("保存失败");
        }
    }
}
